/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package fplaton.ui;

import fplaton.db.SQLiteJDBC;
import static fplaton.helper.Validation.isNullorEmpty;
import java.awt.event.KeyEvent;
import java.io.File;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;

/**
 *
 * @author vasovourka
 */
public final class addteacher extends javax.swing.JFrame {

    /**
     * Creates new form addteacher
     */
    public addteacher() {

        initComponents();
        initjTable();

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        beginPanel = new javax.swing.JPanel();
        nameLabel = new javax.swing.JLabel();
        lNameLabel = new javax.swing.JLabel();
        phoneLabel = new javax.swing.JLabel();
        mailLabel = new javax.swing.JLabel();
        specialtyLabel = new javax.swing.JLabel();
        nameTField = new javax.swing.JTextField();
        lNameTField = new javax.swing.JTextField();
        phoneTField = new javax.swing.JTextField();
        mailTField = new javax.swing.JTextField();
        specialtyCombo = new javax.swing.JComboBox();
        addButton1 = new javax.swing.JButton();
        viewTeachers = new javax.swing.JLabel();
        jScrollPane4 = new javax.swing.JScrollPane();
        teachersTable = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        beginPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Καταχώρηση Καθηγητή", javax.swing.border.TitledBorder.LEFT, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Abadi MT Condensed Extra Bold", 1, 12), new java.awt.Color(102, 102, 102))); // NOI18N

        nameLabel.setText("Όνομα:");

        lNameLabel.setText("Επώνυμο:");

        phoneLabel.setText("Τηλέφωνο:");

        mailLabel.setText("e-mail:");

        specialtyLabel.setText("Ειδικότητα");

        nameTField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nameTFieldActionPerformed(evt);
            }
        });

        lNameTField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                lNameTFieldActionPerformed(evt);
            }
        });

        phoneTField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                phoneTFieldActionPerformed(evt);
            }
        });
        phoneTField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                phoneTFieldKeyTyped(evt);
            }
        });

        specialtyCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { " ", "Μαθηματικός", "Φυσικός", "Προγραμματιστής", "Φιλόλογος", " " }));

        addButton1.setText("Καταχώρηση");
        addButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout beginPanelLayout = new javax.swing.GroupLayout(beginPanel);
        beginPanel.setLayout(beginPanelLayout);
        beginPanelLayout.setHorizontalGroup(
            beginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(beginPanelLayout.createSequentialGroup()
                .addGroup(beginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(beginPanelLayout.createSequentialGroup()
                        .addGap(49, 49, 49)
                        .addGroup(beginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(specialtyLabel)
                            .addGroup(beginPanelLayout.createSequentialGroup()
                                .addGroup(beginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lNameLabel)
                                    .addComponent(phoneLabel)
                                    .addComponent(nameLabel)
                                    .addComponent(mailLabel))
                                .addGap(136, 136, 136)
                                .addGroup(beginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(nameTField, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(phoneTField, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(lNameTField, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(mailTField, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(specialtyCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                    .addGroup(beginPanelLayout.createSequentialGroup()
                        .addGap(40, 40, 40)
                        .addComponent(addButton1)))
                .addContainerGap(37, Short.MAX_VALUE))
        );
        beginPanelLayout.setVerticalGroup(
            beginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(beginPanelLayout.createSequentialGroup()
                .addGap(39, 39, 39)
                .addGroup(beginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(beginPanelLayout.createSequentialGroup()
                        .addComponent(nameLabel)
                        .addGap(43, 43, 43)
                        .addComponent(lNameLabel)
                        .addGap(47, 47, 47)
                        .addComponent(phoneLabel)
                        .addGap(34, 34, 34)
                        .addGroup(beginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(mailLabel)
                            .addComponent(mailTField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(beginPanelLayout.createSequentialGroup()
                        .addComponent(nameTField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(31, 31, 31)
                        .addComponent(lNameTField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(29, 29, 29)
                        .addComponent(phoneTField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(23, 23, 23)
                .addComponent(specialtyLabel)
                .addGroup(beginPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(beginPanelLayout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(addButton1)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, beginPanelLayout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 7, Short.MAX_VALUE)
                        .addComponent(specialtyCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(59, 59, 59))))
        );

        viewTeachers.setText("ΚΑΤΑΧΩΡΗΜΕΝΟΙ ΚΑΘΗΓΗΤΕΣ");

        teachersTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null}
            },
            new String [] {
                "id", "Όνομα", "Επώνυμο", "Τηλέφωνο", "e-mail", "Ειδικότητα"
            }
        ));
        jScrollPane4.setViewportView(teachersTable);
        if (teachersTable.getColumnModel().getColumnCount() > 0) {
            teachersTable.getColumnModel().getColumn(5).setMaxWidth(100);
        }

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(12, 12, 12)
                .addComponent(beginPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(viewTeachers)
                    .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 599, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(0, 131, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(131, 131, 131)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(beginPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(viewTeachers)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 386, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(407, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void nameTFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nameTFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_nameTFieldActionPerformed

    private void lNameTFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_lNameTFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_lNameTFieldActionPerformed

    private void phoneTFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_phoneTFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_phoneTFieldActionPerformed

    private void phoneTFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_phoneTFieldKeyTyped
        char c = evt.getKeyChar();
        if (!(Character.isDigit(c)) || c == KeyEvent.VK_DELETE
                || phoneTField.getText().length() >= 10) {

            getToolkit().beep();
            evt.consume();
    }//GEN-LAST:event_phoneTFieldKeyTyped
    }
    private void addButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButton1ActionPerformed
        String name = null, lName = null, phone = null, mail = null, specialty = null;
        if (checkNullFields() == false) {
            JOptionPane.showMessageDialog(this, "έχετε κενά πεδία!");
        } else {
            name = nameTField.getText();
            lName = lNameTField.getText();
            phone = phoneTField.getText();

            mail = mailTField.getText();
            specialty = specialtyCombo.getSelectedItem().toString();

            try {
                SQLiteJDBC connection = createDBtable();
                insterToDBtable(connection, name, lName, phone, mail, specialty);
                ResultSet r = connection.executeQuery("select * from TEACHERS");
                showDBtable(r);
                JOptionPane.showMessageDialog(this, "Ο βαθμός καταχωρήθηκε.");
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(null, e);
            }

        }

    }

    public boolean insterToDBtable(SQLiteJDBC connection, String name,
            String lName, String phone, String mail, String specialty) throws SQLException {
        PreparedStatement prep = connection.conn.prepareStatement(
                "INSERT INTO TEACHERS VALUES(?, ?, ?, ?, ?, ?);");

        prep.setString(2, name);
        prep.setString(3, lName);
        prep.setString(4, phone);
        prep.setString(5, mail);
        prep.setString(6, specialty);
        connection.conn.setAutoCommit(false);
        prep.execute();
        connection.conn.setAutoCommit(true);
        return true;
    }

    public boolean checkNullFields() {
        boolean verify=true;

        if (isNullorEmpty(nameTField.getText())) {
            verify = false;
        } 

        if (isNullorEmpty(lNameTField.getText())) {
            verify = false;
        } 
        if (isNullorEmpty(phoneTField.getText())) {
            verify = false;
        } 
        if (isNullorEmpty(mailTField.getText())) {
            verify = false;
        } 
        
        if (isNullorEmpty(specialtyCombo.getSelectedItem().toString())) {
            verify = false;
        } 
        return verify;

    }

    public boolean showDBtable(ResultSet r) {
        if (r == null) {
            return false;
        }
        try {
            int row = 0;
            int col = 0;
            while (r.next()) {

                String[] str = {r.getString("ID"), r.getString("NAME"),
                    r.getString("LNAME"), r.getString("PHONE"),
                    r.getString("MAIL"), r.getString("SPECIALTY")};
                int i = 0;
                for (col = 0; col <= 5; col++) {
                    teachersTable.setValueAt(str[i], row, col);

                    i++;
                }

                row++;

            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(null, e);
        }

        return true;

    }//GEN-LAST:event_addButton1ActionPerformed

    public SQLiteJDBC createDBtable() throws SQLException {
        SQLiteJDBC connection = new SQLiteJDBC("frontistirio.db");

        String create_table = "CREATE TABLE IF NOT EXISTS TEACHERS "
                + "(ID INTEGER PRIMARY KEY  AUTOINCREMENT,"
                + " NAME          TEXT    NOT NULL,"
                + " LNAME         TEXT    NOT NULL,"
                + " PHONE         TEXT    NOT NULL,"
                + " MAIL          TEXT    NOT NULL,"
                + " SPECIALTY     TEXT    NOT NULL)";
        connection.execute(create_table);

        return connection;
    }

    public boolean initjTable() {

        if (fileExists() == true) {
            try {
                SQLiteJDBC connection = createDBtable();
                ResultSet r = connection.executeQuery("select * from TEACHERS");
                showDBtable(r);
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(null, e);
            }

        }
        return true;
    }

    public boolean fileExists() {
        File f = new File("/Users/vasovourka/NetBeansProjects/fplaton", "frontistirio.db");
        if (f.exists()) {

            return true;
        } else {
            int n = JOptionPane.showConfirmDialog(this, "db file doesn't exist!Create new one?",
                    "message", JOptionPane.OK_CANCEL_OPTION);
            if (n == JOptionPane.OK_OPTION) {

            } else if (n == JOptionPane.CANCEL_OPTION) {
                System.exit(0);
            }

            return false;

        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;

                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(addteacher.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(addteacher.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(addteacher.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(addteacher.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new addteacher().setVisible(true);
            }
        });
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addButton1;
    private javax.swing.JPanel beginPanel;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JLabel lNameLabel;
    private javax.swing.JTextField lNameTField;
    private javax.swing.JLabel mailLabel;
    private javax.swing.JTextField mailTField;
    private javax.swing.JLabel nameLabel;
    private javax.swing.JTextField nameTField;
    private javax.swing.JLabel phoneLabel;
    private javax.swing.JTextField phoneTField;
    private javax.swing.JComboBox specialtyCombo;
    private javax.swing.JLabel specialtyLabel;
    private javax.swing.JTable teachersTable;
    private javax.swing.JLabel viewTeachers;
    // End of variables declaration//GEN-END:variables
}
